import React from 'react';
import { Modal } from 'antd';
import { ModalProps } from 'antd/lib/modal';

type Props = ModalProps & {
  children: any;
  clone?: boolean;
  triggerContent: any;
}

type State = {
  show: boolean;
  modalProps: ModalProps;
}

export type CloneProps = {
  submitStop?(): any;
  closeModal?(): any;
  submitLoading?(): any;
  listenOk?(fn: Function): any;
}

class ModalPro extends React.PureComponent<Props, State> {
  static defaultProps = {
    clone: true,
    triggerContent: null
  }

  state: State = {
    show: false,
    modalProps: {}
  }

  private onOkFn: any = null;

  private onTriggerClick = () => {
    this.setState({ show: true });
  }

  private onClose = () => {
    setTimeout(() => {
      const { modalProps } = this.state;
      const { confirmLoading } = modalProps;
      !confirmLoading && this.setState({ show: false });
    });
  }

  /*
  * 设置modal的props
  * */
  private setModalProps = (props: ModalProps) => {
    this.setState({ modalProps: props });
  }

  /*
  * 监听ok点击
  * */
  private listenOk = (fn: Function) => {
    this.onOkFn = fn;
  }

  /*
  * 提交时，需要加上loading
  * */
  private submitLoading = () => {
    this.setModalProps({
      confirmLoading: true,
      cancelButtonProps: { disabled: true }
    });
  }

  /*
  * 提交结束，关闭loading
  * */
  private submitStop = () => {
    this.setModalProps({
      confirmLoading: false,
      cancelButtonProps: { disabled: false }
    });
  }

  private onOkClick = () => this?.onOkFn?.();

  render() {
    const {
      show,
      modalProps
    } = this.state;
    const {
      clone,
      children,
      triggerContent,
      ...rest
    } = this.props;
    return (
      <React.Fragment>
        {React.cloneElement(children, {
          onClick: this.onTriggerClick
        })}
        <Modal
          {...rest}
          {...modalProps}
          visible={show}
          centered={true}
          destroyOnClose={true}
          onOk={this.onOkClick}
          onCancel={this.onClose}
        >
          {clone ? React.cloneElement(triggerContent, {
            listenOk: this.listenOk,
            closeModal: this.onClose,
            submitStop: this.submitStop,
            submitLoading: this.submitLoading,
          }) : triggerContent}
        </Modal>
      </React.Fragment>
    )
  }
}

export default ModalPro;
